package com.hrm.filter;

import com.hrm.commons.beans.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class LoginFilter implements Filter {

    /*不进行过滤的页面，处理器方法或其他静态资源*/
    String[] IG_URI = {"/index.jsp","loginForm.jsp","/login","/",".css",".js",".jpg"};


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        /*强制类型转换*/
        HttpServletRequest request1 = (HttpServletRequest) request;
        HttpServletResponse response1 = (HttpServletResponse) response;
        /*获取请求的URI*/
        String requestURI = request1.getRequestURI();
        /*循环判断本次请求的URI是否为数组中定义的字符串*/
        for(String s:IG_URI){
            /*如果本次请求是不进行过滤的请求*/
            if(requestURI.endsWith(s)){
                /*直接放行*/
                chain.doFilter(request1,response1);
                return;
            }
        }
      /*获取用户登陆的信息*/
        User login_user = (User) request1.getSession().getAttribute("login_user");

        /*用户已经登陆*/
        if(login_user != null){
            chain.doFilter(request1,response1);
        }
        else{
            /*用户未登录*/
            request1.setAttribute("login_error","您还未登录，请登陆后访问！");
            request1.getRequestDispatcher("/index.jsp").forward(request1,response1);
        }
    }
}
